package com.graduation.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.graduation.common.autoconfigure.auth.JwtProperties;
import com.graduation.common.constans.BizConstants;
import com.graduation.common.constans.RedisConstants;
import com.graduation.common.utils.JwtUtil;
import com.graduation.common.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Slf4j
public class LoginUserInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    private final JwtProperties jwtProperties;

    public LoginUserInterceptor(StringRedisTemplate stringRedisTemplate, JwtProperties jwtProperties) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.jwtProperties = jwtProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获得token
        String token = request.getHeader(BizConstants.USER_TOKEN_HEADER);
        if (StrUtil.isBlank(token)) {
            return true;
        }

        // 解析token拿到uuid
        Claims claims = JwtUtil.parseToken(token, jwtProperties.getPublicKey());
        if (claims == null) {
            return true;
        }
        String uuid = claims.get(BizConstants.TOKEN_LOGIN_INFO, String.class);
        if (StrUtil.isBlank(uuid)) {
            return true;
        }

        // 从redis获取登录用户信息
        String key = RedisConstants.LOGIN_CACHE_KEY_PREFIX + uuid;
        String redisUserInfo = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(redisUserInfo)) {
            return true;
        }

        // 转换实际数据
        Long userId = Long.valueOf(redisUserInfo);

        // 将信息存储到ThreadLocal中
        UserContext.setUser(userId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserContext.removeUser();
    }
}
